/*
 * @lc app=leetcode.cn id=289 lang=cpp
 * @lcpr version=30204
 *
 * [289] 生命游戏
 */


// @lcpr-template-start
using namespace std;
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// @lcpr-template-end
// @lc code=start
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
        int n = board[0].size();
        
        // 定义方向数组，用于遍历周围的8个方向
        vector<pair<int, int>> directions = {
            {-1, -1},   {-1, 0},    {-1, 1},
            { 0, -1},               { 0, 1},
            { 1, -1},   { 1, 0},    { 1, 1}
        };

        // 遍历每个细胞
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int liveNeighbors = 0;

                // 计算周围活细胞的数量
                for (auto& dir : directions) {
                    int ni = i + dir.first;
                    int nj = j + dir.second;
                    if (ni >= 0 && ni < m && nj >= 0 && nj < n && abs(board[ni][nj]) == 1) {
                        liveNeighbors++;
                    }
                }

                // 根据规则更新状态
                if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
                    board[i][j] = -1; // 活变死
                }
                if (board[i][j] == 0 && liveNeighbors == 3) {
                    board[i][j] = 2; // 死变活
                }
            }
        }

        // 更新 board 到下一状态
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] > 0) {
                    board[i][j] = 1; 
                } else {
                    board[i][j] = 0; 
                }
            }
        }
    }
};
// @lc code=end



/*
// @lcpr case=start
// [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n
// @lcpr case=end

// @lcpr case=start
// [[1,1],[1,0]]\n
// @lcpr case=end

 */

